@icon("res://游戏图标.png")
extends Resource
class_name ItemDataBase
# 定义一个资源类，用来作为某种物品的数据库

@export var item_dic:Dictionary
@export var max_id:int = 0
var item_dic_array:Array=[]
func add_item(IteminfoDictionary):
	# add Item info 
	# Info should be a dictionary, and contains "id" as key
	if item_dic.has(IteminfoDictionary.id):
		print_debug("Id already exist, Use force_add_item() func to replace Item")
		return
	if IteminfoDictionary.has("id"):
		item_dic[IteminfoDictionary.id] = IteminfoDictionary
	else:
		print_debug("ItemInfo do not have key 'id' ")


func force_add_item(IteminfoDictionary):
	if IteminfoDictionary.has("id"):
		item_dic[IteminfoDictionary.id] = IteminfoDictionary
	else:
		print_debug("ItemInfo do not have key 'id' ")


func remove_itemById(ItemID):
	# remove_item By Id
	if item_dic.has(ItemID):
		item_dic.erase(ItemID)


func save_as_resource(FilePath:String):
	# 将整个资源文件保存到path
	# 这里应该判断路径中的目录是否存在，不存在的话要新建目录
	ResourceSaver.save(self, FilePath)


func load_from_csv(CSVPath:String):
	# 从csv文件中读取数据库
	var file:FileAccess = FileAccess.open(CSVPath,FileAccess.READ)
	var content:String = file.get_as_text()
	var CsvList:PackedStringArray = content.split("\r\n")
	# 按行分割
	var Keys:Array = CsvList[0].split(",")
	print(Keys)
	CsvList.remove_at(0)
	# 得到首行的Keys并移除首行
	for LineIndex in range(len(CsvList)):

		var datalist:PackedStringArray = CsvList[LineIndex].split(",")
		
		var DicTemp:Dictionary = {}
		for dataIndex in range(len(datalist)):
			DicTemp[Keys[dataIndex]] = datalist[dataIndex]
		if DicTemp.has("id"):
			max_id = max(max_id, int(DicTemp["id"]))
			item_dic[DicTemp["id"]] = DicTemp.duplicate(true)
			if DicTemp.has("icon"):
				item_dic_array.append(DicTemp)
			# 将相应的数据储存整合为新字典，并保存到字典中
	
func save_to_csv(FilePath:String):
	# 检查数据是否存在
	if item_dic.is_empty():
		print_debug("Item database is empty, nothing to save.")
		return false
	
	# 打开文件
	var file := FileAccess.open(FilePath, FileAccess.WRITE)
	if file == null:
		print_debug("Failed to open file for writing: %s" % FilePath)
		return false

	# 获取所有键名（表头）
	var items = item_dic.values()
	var keys = items.get(0).keys()
	# 写入表头
	file.store_line(",".join(keys))
	
	# 写入数据行
	for item in items:
		var row:Array = []
		for key in keys:
			var value = item[key]
			# 处理可能的逗号（转换为分号）
			if typeof(value) == TYPE_STRING:
				value = value.replace(",", ";")
			row.append(str(value))
		file.store_line(",".join(row))
	
	# 关闭文件
	file.close()
	return true
